<?php
    function hash_on_db($hash){
        $hash = mysql_real_escape_string($hash);
        $sql_result = DB::query("SELECT id, username, password FROM users WHERE login_hash = '".$hash."'");
        $result = DB::row($sql_result);
        if ($result != null){
            global $user;
            list($user['id'], $user['username'], $user['password']) = $result;
            return true;
        }  
        return false;
       
    }
    function logged_in(){
        if(!isset($_COOKIE['login_hash']) || !hash_on_db($_COOKIE['login_hash'])){
            return false;
        }
        return true;
    }
    function logout(){
        setcookie ('login_hash', FALSE);
        add_success("Sėkmingai atsijungta");
        include 'GUI/Login/login.php';
        exit;
    }
    
    function login($user, $password, $remember = false) {
        if (logged_in()) {
            return;
        }
        $user = mysql_escape_string($user);
        $sql_result = DB::query(sprintf(
                "SELECT * FROM users WHERE username = '%s' AND password = '%s'", 
                $user, 
                md5($password)
        ));
        $result = DB::row($sql_result);
        if($result == false){
            $help_link = '<br/><a href="javascript:popupW(\'GUI/Help/help.php?file=login\')">Pamiršote slaptažodį?</a>';
            add_error("Klaidingas vartotojo vardas ir/ar slaptažodis" . $help_link);
            return;
        }else{
            $hash = md5($user . microtime() . md5($password));
            $sql_result = DB::query(sprintf(
                    "UPDATE users SET login_hash='".$hash."' WHERE username = '%s'",
                    $user
            ));
            $time = 0;
            if($remember){
                $time = time()+60*60*24*30;
            }
            setcookie ('login_hash', $hash, $time);
            return true;
        }
    }
    
    if(isset($_POST['username']) && isset($_POST['password'])){
        if (login($_POST['username'], $_POST['password'], array_key_exists('rememberMe', $_POST))) {
            $ssl = array_key_exists('REDIRECT_HTTPS', $_SERVER) ? 'https://' : 'http://';
            $link = $ssl . $_SERVER['HTTP_HOST'] . $_SERVER["REQUEST_URI"];
            if (substr($link, -strlen('?logout')) == '?logout') {
                $link = substr($link, 0, strlen($link)-strlen('?logout'));
            }
            header("Location: $link");
        }
    }

    
?>
